import {
	memo,
	createContext,
	useContext,
	PropsWithChildren,
	useState,
	useRef,
	createRef
} from 'react';
import type { AnyObject } from './type';

type ParamType = { [key: string]: any };
const initStore = {
	tableHeight: 0,
	payload: { pageNo: 1, pageSize: 10, param: {} },
	tableListRef: createRef<{ list: AnyObject[]; isPageChange: boolean; hasTotal: boolean }>(),
	setTableHeightAction: (height: number) => {},
	setPageInfoAction: (pageNo: number, pageSize: number) => {},
	setParamAction: (data: ParamType, type: 'search' | 'reset') => {}
};

const DataContext = createContext(initStore);

export const ContextProvider = memo((props: PropsWithChildren) => {
	const [tableHeight, setTableHeight] = useState(0);
	const [payload, setPayload] = useState({ pageNo: 1, pageSize: 10, param: {} });
	const tableListRef = useRef({ list: [], isPageChange: false, hasTotal: true });

	const action = {
		setParamAction(data: ParamType, type: 'search' | 'reset') {
			tableListRef.current.isPageChange = false;
			if (type === 'search') {
				setPayload((prev) => ({ ...prev, param: { ...prev.param, ...data }, pageNo: 1 }));
			} else {
				setPayload((prev) => ({ ...prev, param: {}, pageNo: 1 }));
			}
		},
		setPageInfoAction(pageNo: number, pageSize: number) {
			tableListRef.current.isPageChange = true;
			setPayload((prev) => ({ ...prev, pageNo, pageSize }));
		},
		setTableHeightAction(height: number) {
			setTableHeight(height);
		}
	};

	return (
		<DataContext.Provider value={{ payload, tableHeight, tableListRef, ...action }}>
			{props.children}
		</DataContext.Provider>
	);
});

export const useDataContext = () => {
	return useContext(DataContext);
};
